from src.infrastructure.db.models import Server


def generate_proxy_string(proxy_user: str, proxy_password: str, proxy_port: int, modem_ip: str, inner_ip: str) -> str:
    return (
        f"auth strong\n"
        f"users {proxy_user}:CL:{proxy_password}\n"
        f"allow {proxy_user}\n"
        f"deny {proxy_user} * $/usr/local/3proxy/banlist.list * * *\n"
        f"proxy -n -a -p{proxy_port} -i{inner_ip} -e{modem_ip}\n"
        f"flush"
    )

    # Блок с кэшированием (пока отключен)
    # return (
    #     f"auth strong\n"
    #     f"users {proxy_user}:CL:{proxy_password}\n"
    #     f"allow {proxy_user} * * * * {proxy_port}\n"
    #     f"deny {proxy_user} * $/usr/local/3proxy/banlist.list  * * * 1001 {proxy_port}\n"
    #     f"allow * * * {proxy_port}\n"
    #     f"parent 1000 http 5.9.95.220 3030 admin R2B3GJT7dQG\n"
    #     f"proxy -n -a -p{proxy_port} -i192.168.99.149 -e{modem_ip}\n"
    #     f"flush"
    # )


def generate_iponly_proxy_string(ip_address: str, proxy_port: int, modem_ip: str) -> str:
    return (
        f"auth iponly\n"
        f"allow * {ip_address}\n"
        f"proxy -n -a -p{proxy_port} -i192.168.99.149 -e{modem_ip}\n"
        f"flush"
    )


def generate_reload_file_content(server: Server, modem_ip: str) -> str:
    return (
        f"#! /bin/bash\n"
        f"<?php \n"
        f'$connection = ssh2_connect("192.168.99.149", 22);\n\n'
        f"if(!$connection) throw new Exception('Не удается подключиться к серверу');\n"
        f"if(!ssh2_auth_password($connection, '{server.login}', '{server.password}')) throw new Exception('Неверный пользователь или пароль');\n\n"
        f"$script = '/root/rekonekt.sh -r 4G  -i {modem_ip.replace('00', '')}';\n"
        f"$stream = ssh2_exec($connection, $script);\n"
        f"stream_set_blocking($stream, true);\n"
        f"$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);\n"
        f"echo $result = stream_get_contents($stream_out);\n"
        f"?>\n"
    )
